<?php
/**
 * Created by PhpStorm.
 * User: zjx
 * Date: 2016/11/25
 * Time: 10:32
 */

namespace App\Services\Utils;

use App\Http\Models\BosModel;
use Intervention\Image\ImageManagerStatic;

class BosImageKeyProcessor
{
    /**
     * @see Bos Image Service Docs
     * @see https://cloud.baidu.com/doc/BOS/ImgService.html#.01.EA.A9.66.20.89.9A.78.6B.6D.E8.EE.63.2A.3D.3B
     *
     * 支持图片规格
        支持的原图格式：jpg、png、bmp、webp、gif、tiff。
        支持的目标图格式：jpg、png、bmp、webp。
        支持图片大小为10MB，且图片长和宽不大于4096 px。
     *
     */
    const VALIDATE_IMG_EXTENSIONS = [
        'jpg', 'jpeg', 'png', 'bmp', 'webp'
    ];

    /**
     * 降低 bos 图片质量，防止 android 无法显示
     *
     * @v2017 bucket : benyamin
     * @v2017 bos_key : debug_test/peacock_advert/origin.jpg
     *
     * @param string $bos_key
     * @return bool
     */
    public static function process($bos_key)
    {
        if (! static::isBosKeyTypeValidate($bos_key)) return false;

        $bos_client = new BosModel();

        $origin_img_url = $bos_client->getStaticUrl($bos_key);

        // get processor url
        $process_img_url = static::getProcessImgUrl($origin_img_url);

        // save deQuality image
        $temp_img = static::tempSaveBosImage($process_img_url, $bos_key);

        // reUpload img with same key
        $bos_client->uploadLocalFile($temp_img, $bos_key);

        // clean tmp img
        unlink($temp_img);

        return true;
    }

    /**
     * @param $process_img_url
     * @param $bos_key
     * @return string
     */
    private static function tempSaveBosImage($process_img_url, $bos_key)
    {
        $save_path = storage_path($bos_key);

        SafeMakeDir::makeFileDir($save_path);

        ImageManagerStatic::make($process_img_url)
            ->save($save_path);

        return $save_path;
    }

    /**
     *
     * @param $origin_img_url
     * @return string
     */
    private static function getProcessImgUrl($origin_img_url)
    {
        $quality_processor = '@q_100';

        $process_img_url = $origin_img_url . $quality_processor;

        return $process_img_url;
    }

    /**
     * @param $bos_key
     * @return bool
     */
    private static function isBosKeyTypeValidate($bos_key)
    {
        $extension = pathinfo($bos_key, PATHINFO_EXTENSION);

        return in_array($extension, static::VALIDATE_IMG_EXTENSIONS);
    }

}